using System;
using System.Text.RegularExpressions;

namespace NEnsure.Rules
{
	public class RegexRule : BaseBusinessRule<string>, IBusinessRule<string>
	{
		private readonly string _pattern;

		public override string RuleKey
		{
			get { return "Regex Rule"; }
		}

		public RegexRule(string pattern)
			: this(pattern, "Property '{key}' with value '{value}' does not match pattern: " + pattern)
		{
			
		}

		public RegexRule(string pattern, string defaultErrorFormat)
			: base(defaultErrorFormat)
		{
			if (string.IsNullOrEmpty(pattern))
			{
				throw new ArgumentNullException("pattern");
			}

			_pattern = pattern;
		}

		public bool IsBrokenBy(string value)
		{
			if (value == null)
			{
				value = string.Empty;
			}

			return !Regex.IsMatch(value, _pattern);
		}
	}
}
